//
//  YSTChatViewController.m
//  YSTChatUIKit
//
//  Created by 王文文 on 2018/2/8.
//  Copyright © 2018年 王文文. All rights reserved.
//

#import "YSTChatViewController.h"
#import "ChatKeyBoard.h"
#import "ChatMessageTextCell.h"
#import "ChatMessageFrame.h"
#import "ChatMessageIconCell.h"




@interface YSTChatViewController ()<ChatKeyBoardDelegate,ChatKeyBoardDataSource,UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong) UITableView *mainTableView;

@property (nonatomic, strong) GJKeyboard *customKeyBoard; //自定义键盘

@property (nonatomic, strong) ChatKeyBoard *chatKeyBoard;

@property(nonatomic, strong) NSMutableArray *dataSource; //数据源

@end

@implementation YSTChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self mainTableView];
    
    self.dataSource = [NSMutableArray array];
    
    self.chatKeyBoard = [ChatKeyBoard keyBoard];
    self.chatKeyBoard.delegate = self;
    self.chatKeyBoard.dataSource = self;
    
    self.chatKeyBoard.keyBoardStyle = KeyBoardStyleChat;
    
     self.chatKeyBoard.associateTableView = self.mainTableView;
    
    [self.view addSubview:self.chatKeyBoard];
    
    [self initData];
//    dispatch_async(dispatch_get_main_queue(), ^{
//
//        if (kLines > 0) {
//            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:kLines-1 inSection:0];
//            [self.mainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionNone animated:NO];
//        }
//    });
    

}

#pragma mark -- ChatKeyBoardDataSource
- (NSArray<MoreItem *> *)chatKeyBoardMorePanelItems
{
    MoreItem *item1 = [MoreItem moreItemWithPicName:@"sharemore_location" highLightPicName:nil itemName:@"位置"];
    MoreItem *item2 = [MoreItem moreItemWithPicName:@"sharemore_pic" highLightPicName:nil itemName:@"图片"];
    MoreItem *item3 = [MoreItem moreItemWithPicName:@"sharemore_video" highLightPicName:nil itemName:@"拍照"];
    MoreItem *item4 = [MoreItem moreItemWithPicName:@"sharemore_location" highLightPicName:nil itemName:@"位置"];
    MoreItem *item5 = [MoreItem moreItemWithPicName:@"sharemore_pic" highLightPicName:nil itemName:@"图片"];
    MoreItem *item6 = [MoreItem moreItemWithPicName:@"sharemore_video" highLightPicName:nil itemName:@"拍照"];
    MoreItem *item7 = [MoreItem moreItemWithPicName:@"sharemore_location" highLightPicName:nil itemName:@"位置"];
    MoreItem *item8 = [MoreItem moreItemWithPicName:@"sharemore_pic" highLightPicName:nil itemName:@"图片"];
    MoreItem *item9 = [MoreItem moreItemWithPicName:@"sharemore_video" highLightPicName:nil itemName:@"拍照"];
    return @[item1, item2, item3, item4, item5, item6, item7, item8, item9];
}

- (NSArray<ChatToolBarItem *> *)chatKeyBoardToolbarItems
{
    ChatToolBarItem *item1 = [ChatToolBarItem barItemWithKind:kBarItemFace normal:@"face" high:@"face_HL" select:@"keyboard"];
    
    ChatToolBarItem *item2 = [ChatToolBarItem barItemWithKind:kBarItemVoice normal:@"voice" high:@"voice_HL" select:@"keyboard"];
    
    ChatToolBarItem *item3 = [ChatToolBarItem barItemWithKind:kBarItemMore normal:@"more_ios" high:@"more_ios_HL" select:nil];
    
    ChatToolBarItem *item4 = [ChatToolBarItem barItemWithKind:kBarItemSwitchBar normal:@"switchDown" high:nil select:nil];
    
    return @[item1, item2, item3, item4];
}

- (NSArray<FaceThemeModel *> *)chatKeyBoardFacePanelSubjectItems
{
    NSMutableArray *subjectArray = [NSMutableArray array];
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"emoji" ofType:@"plist"];
    NSDictionary *faceDic = [NSDictionary dictionaryWithContentsOfFile:plistPath];
    NSArray *allkeys = faceDic.allKeys;
    
    FaceThemeModel *themeM = [[FaceThemeModel alloc] init];
    themeM.themeStyle = FaceThemeStyleCustomEmoji;
    
    NSMutableArray *modelsArr = [NSMutableArray array];
    
    for (int i = 0; i < allkeys.count; ++i) {
        NSString *name = allkeys[i];
        FaceModel *fm = [[FaceModel alloc] init];
        fm.faceTitle = name;
        fm.faceIcon = [faceDic objectForKey:name];
        [modelsArr addObject:fm];
    }
    themeM.faceModels = modelsArr;
    
    [subjectArray addObject:themeM];
    
    return subjectArray;
}

#pragma mark -- 语音状态
- (void)chatKeyBoardDidStartRecording:(ChatKeyBoard *)chatKeyBoard
{
    //    self.voiceState.text = @"正在录音";
}
- (void)chatKeyBoardDidCancelRecording:(ChatKeyBoard *)chatKeyBoard
{
    //    self.voiceState.text = @"已经取消录音";
}
- (void)chatKeyBoardDidFinishRecoding:(ChatKeyBoard *)chatKeyBoard
{
    //    self.voiceState.text = @"已经完成录音";
}
- (void)chatKeyBoardWillCancelRecoding:(ChatKeyBoard *)chatKeyBoard
{
    //    self.voiceState.text = @"将要取消录音";
}
- (void)chatKeyBoardContineRecording:(ChatKeyBoard *)chatKeyBoard
{
    //    self.voiceState.text = @"继续录音";
}

- (void)initData {
    
    ChatMessageFrame *cellFrame = [[ChatMessageFrame alloc]init];
    ChatMessage *message = [[ChatMessage alloc]init];
    message.userType = userTypeMe;
    message.userId = 0;
    NSString *Lmessage = @"在村里，Lz辈分比较大，在我还是小屁孩的时候就有大人喊我叔了，这不算糗[委屈]。 成年之后，鼓起勇气向村花二丫深情表白了(当然是没有血缘关系的)[害羞]，结果她一脸淡定的回绝了:“二叔！别闹……”[尴尬]";
    message.messageContent = Lmessage;
    cellFrame.message = message;
    [self.dataSource addObject:cellFrame];
//    NSMutableArray *messageArray = [LiuqsMessageDataBase queryData:nil];
//    [messageArray enumerateObjectsUsingBlock:^(ChatMessage *message, NSUInteger idx, BOOL * _Nonnull stop) {
//        ChatMessageFrame *cellFrame = [[ChatMessageFrame alloc]init];
//        cellFrame.message = message;
//        [self.dataSource addObject:cellFrame];
//    }];
//    [self.chatList reloadData];
    [self ScrollTableViewToBottom];
}

//滚动到底部
- (void)ScrollTableViewToBottom {
    
    if (!self.dataSource.count) {return;}
    if (self.dataSource.count - 1 >= 1) {
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.dataSource.count - 1 inSection:0];
        [self.mainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
    }
}

#pragma mark -- 更多
- (void)chatKeyBoard:(ChatKeyBoard *)chatKeyBoard didSelectMorePanelItemIndex:(NSInteger)index {
    if (index == 0) {
        //相册
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            picker.allowsEditing = YES;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:^{
            }];
        }
    }
    if (index == 1) {
        //相机
    }
    
    //其余自定义
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *editImage = [info objectForKey:UIImagePickerControllerEditedImage];
    [self dismissViewControllerAnimated:YES completion:^{
//        NSDictionary *dic = @{@"picture": editImage,
//                              @"type": @(messageTypePicture)};
        [self dealTheFunctionData:editImage];
//        NSData* data = UIImageJPEGRepresentation(editImage, 1.0);
//        [self uploadImge:data];
//        [self.delegate UUInputFunctionView:self sendPicture:editImage];
    }];
}

- (void)dealTheFunctionData:(UIImage *)editImage
{
   
        //图片消息
        ChatMessageFrame *cellFrame = [[ChatMessageFrame alloc]init];
        ChatMessage *message = [[ChatMessage alloc]init];
        message.picture = editImage;
        message.userType = userTypeOther;
        message.messageType = messageTypePicture;
        message.userHeadImage = @"鸣人";
        message.userName = @"鸣人";
        message.userId = self.dataSource.count;
        cellFrame.message = message;
        [self.dataSource addObject:cellFrame];
        [self.mainTableView reloadData];
        [UIView animateWithDuration:0.25 animations:^{
            
            [self ScrollTableViewToBottom];
        }];
        

   
    
}
#pragma mark -- 发送文本
- (void)chatKeyBoardSendText:(NSString *)text {
    if (!text.length) {
        return;
    }
    
    //点击发送，发出一条消息
    ChatMessageFrame *cellFrame = [[ChatMessageFrame alloc]init];
    ChatMessage *message = [[ChatMessage alloc]init];
    message.messageContent = text;
    message.userType = userTypeOther;
    message.userHeadImage = @"鸣人";
    message.userName = @"鸣人";
    message.userId = self.dataSource.count;
    cellFrame.message = message;
    [self.dataSource addObject:cellFrame];
    [self.mainTableView reloadData];
    [UIView animateWithDuration:0.25 animations:^{
        
        [self ScrollTableViewToBottom];
    }];

}

#pragma mark -- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    ChatMessageFrame *cellFrame = self.dataSource[indexPath.row];
    if (cellFrame.message.messageType == messageTypeText) {
         static NSString *cellId = @"demo";
        ChatMessageTextCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[ChatMessageTextCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        cell.tag = indexPath.row;
        cell.MessageFrame = cellFrame;
        
        return cell;
    } else {
        ChatMessageIconCell *cell = [tableView dequeueReusableCellWithIdentifier:@"pictureCell"];
        if (!cell) {
            cell = [[ChatMessageIconCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"pictureCell"];
        }
        cell.tag = indexPath.row;
        cell.MessageFrame  = cellFrame;
        return cell;
    }
    
    
   
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChatMessageFrame *cellFrame = [self.dataSource objectAtIndex:indexPath.row];
    return cellFrame.cellHeight;
}



- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self.chatKeyBoard keyboardDown];
}



-(UITableView *)mainTableView {
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-49) style:UITableViewStylePlain];
        [self.view addSubview:_mainTableView];
        _mainTableView.tableFooterView = [UIView new];
         _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
    }
    return _mainTableView;
}

@end
